var express = require('express')
var router = express.Router()

//导入数据库操作模块
var exec = require('../db')
//导入调试的标记
const {
    debug
} = require('../config')

// 查询
router.get('/', async function (req, res) {

    // 搜索多条数据时, 显示的字段:
    let select_fields =
        ' name, age,school,phone,status,companyName,userId,jobName,desprition,img,address'
    //声明sql语句变量
    let sql
    // 获取全部数据列表 GET /articles
    if (JSON.stringify(req.query) == '{}') {
        sql = `SELECT ${select_fields} FROM job_tb,category_tb where job_tb.category_id=category_tb.id && deleted_time is null`
    }

    // 根据标题模糊查询获取数据列表 GET /articles?title=总结
    else if (req.query.title) {
        sql = `SELECT ${select_fields} FROM job_tb job_tb,category_tb where job_tb.category_id=category_tb.id && title like '%${req.query.title}%' && deleted_time is null`
    }


    // 根据作者id获取数据 GET /articles?user_id=2
    else if (req.query.user_id) {
        sql = `SELECT ${select_fields} FROM apply_tb where apply_tb.userId = ${req.query.user_id}  `
    }


    // 数据响应
    try {
        res.send({
            code: 0,
            msg: '查询成功',
            result: await exec(sql),
        })
    } catch (err) {
        res.send({
            code: 1,
            msg: '失败',
            result: debug ? err : '',
        })
    }
})

// 增加数据 
router.post('/', async (req, res) => {
    let {
        name,
        age,
        school,
        phone,
        status,
        companyName,
        userId,
        jobName,
        desprition,
        img,
        address
    } = req.body

    //查询语句
    let sql = `INSERT INTO apply_tb 
    (
        name,
        age,
        school,
        phone,
        status,
        companyName,
        userId,
        jobName,
        desprition,
        img,
        address
        ) VALUES('${name}', '${age}', '${school}', '${phone}', '${status}', '${companyName}', '${userId}', '${jobName}', '${desprition}', '${img}', '${address}')
        `

    try {
        //返回
        const data = await exec(sql)
        res.send({
            code: 0,
            msg: '添加成功',
            result: data.insertId
        })
    } catch (err) {
        res.send({
            code: 1,
            msg: '添加失败',
            result: debug ? err : ''
        })
    }
})




// 软删除 DELETE /articles?id=1
router.delete('/:id', async (req, res) => {
    sql = `delete from apply_tb where id= ${req.params.id}`

    //响应
    try {
        let data = await exec(sql)
        res.send({
            code: 0,
            msg: '删除成功',
            result: ''
        })
    } catch (err) {
        res.send({
            code: 1,
            msg: '删除失败',
            result: debug ? err : ''
        })
    }
})

module.exports = router